% ImageAnalysis Version 1.3

clc;
clear all;
close all;

%Declaration of constant parameters. 
    NULLPHASE=255;
    %PHASE=1;
    NODATA=-9999;

    imageName=input('Input an image name: ','s');
    [token,ext]=strtok(imageName,'.');
    asciiName=strrep(imageName,ext,'.asc');

%Procedures to read a Bitmap image file.
    data=imread(imageName);
    imageSize=size(data);
    width=imageSize(2);
    height=imageSize(1);
    area=width*height;
    %colormap gray;

%Procedures to recognize each single grain.
    data(find(data~=NULLPHASE))=1;
    data(find(data==NULLPHASE))=0;
    [data,num]=bwlabel(data,8);

    RGB= label2rgb(data);
    image(RGB);

%Measure grain properties.
    graindata=regionprops(data,'basic');
    totalArea=imageSize(1)*imageSize(2);
    area=[graindata.Area];
    radius=sqrt(area/pi);
    center=cat(1,graindata.Centroid);
    save('data.mat', 'graindata', 'totalArea', 'area', 'radius', 'center');

%Procedures to write an ASCII file used in the MRA.
    data(find(data==0))=NODATA;

    fID=fopen(asciiName,'w');
        fprintf(fID,'ncols\t%d\n',width);
        fprintf(fID,'nrows\t%d\n',height);
        fprintf(fID,'xllcorner\t%d\n',0);
        fprintf(fID,'yllcorner\t%d\n',0);
        fprintf(fID,'cellsize\t%d\n',1);
        fprintf(fID,'NODATA_value\t%d\n',NODATA);
        for ii=1:1:height
            fprintf(fID,'%d\t',data(ii,:));
            fprintf(fID,'\n');
        end;
    fclose(fID);